#include "command.h"

//命令表
char command_table[7][20] = {"cd", "ls", "pwd", "puts", "gets", "rm", "mkdir_my"};
int command_num = 7;


//去掉字符串末尾的换行符；
//int delete_enter(char** str) {
//    int len = strlen(*str);
//    len--;  //不计算换行符长度
//    (*str)[len] = '\0'; //字符串结束符
//    return 0;
//}

//do_command的目的是给一个com_prase的接口，让其他函数去执行
int do_command(char* command, int fd)
{
    command_t com_prase;
    memset(&com_prase, 0, sizeof(com_prase));
    //在这里去掉command末尾的换行符，-----重要
    //防止它带着换行符到处乱跑！
    //  delete_enter(&command);  //-----client.c中已去掉
    strcpy(com_prase.command, command);  //把命令写到结构体中

    prase(command, &com_prase);

    execute(&com_prase, fd);
    return 0;
}

int prase(char* command, command_t* pcom)
{
    //分离命令 和 [文件名或目录名]
    //存放到command结构体中
    char* p = command;
    int i = 0, j = 0;
    while (*p) {
        if (*p != ' ') {

            pcom->com[i] = *p;
            i++;
            p++;
        }
        else 
            break;
    }
    pcom->com[i] = '\0';
    //    printf("com: %s\n", pcom->com);

    p++;
    while(*p) {
        pcom->name[j] = *p;
        j++;
        p++;
    }
    pcom->name[j] = '\0';
    return 0;

}

int search(char* com)
{
    for (int i = 0; i < command_num; i++) {
        if (!strcmp(com, command_table[i])) {
            return i;
        }
    }
    return -1;
}

//4、执行客户端的命令
void execute(command_t* pcom, int fd)
{  
    int num = search(pcom->com); 
    printf("command in excute: %s\n", pcom->command);
    switch (num) {
    case 0: case 1: case 2: case 5: case 6:
        send_command(pcom->command, fd);
        break;
    case 3:
        choiceHow(fd, pcom);
        break;
    case 4:
        send_command(pcom->command, fd);
        choiceFile(fd,pcom->name);
        break;
    default:
        puts("client: illegal command");
        //若command为空
    }
}

int send_command(char* command, int peerfd) {
    train_t train;
    memset(&train, 0, sizeof(train));
    //执行send发送命令给服务器
    train.length = strlen(command);
    strncpy(train.buf, command, train.length);

    int ret = sendn(peerfd, &train, 4 + train.length);  //4,length长度，train.length内容长度
    printf("send ret = %d\n", ret);
    if (-1 == ret) {
        puts("sendn failed 0");
    }
    return 0;
}
